package com.jt.blog.controller;

import com.jt.blog.common.exception.JsonResponseException;
import com.jt.blog.common.model.Page;
import com.jt.blog.common.model.Response;
import com.jt.blog.common.redis.util.RedisUtil;
import com.jt.blog.dto.CategoryDto;
import com.jt.blog.model.Blog;
import com.jt.blog.model.BlogStatistics;
import com.jt.blog.model.User;
import com.jt.blog.service.BlogReadService;
import com.jt.blog.service.BlogStatisticsService;
import com.jt.blog.service.CategoryService;
import com.jt.blog.service.UserService;
import com.jt.blog.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author : 戴瑞
 * @Description :前台控制器
 * @create : 2017-05-25 18:20
 **/
@Controller
public class FrontController extends CommonController {
    @Autowired
    private BlogReadService blogReadService;

    @Autowired
    private BlogStatisticsService blogStatisticsService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;



    @RequestMapping("")
    public String index(Model model, Page<Blog> page, BlogQuery query, HttpServletRequest request,HttpSession session) {
        query.setPersonal(0);
        String username;
        Map pathVar = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        String userName = (String) pathVar.get("userName");
        if (userName==null){
            username="admin";
        }else {
            username=userName;
        }

        // 根据用户名来查询博主的ID
        Response<User> userResponse = userService.selectByUserName(username);
        if (userResponse.isSuccess()) {
            query.setUserId(userResponse.getResult().getId());
        }
        session.setAttribute("username",username);
        session.setAttribute("userId",userResponse.getResult().getId());
        Response<Page<Blog>> response = blogReadService.page(page, query);
        if (!response.isSuccess()) {
            throw new JsonResponseException(response.getError());
        }
        model.addAttribute("page", response.getResult());
        model.addAttribute("query", query);
        List<CategoryDto> categories = categoryService.listAndCount(userResponse.getResult().getId());
        model.addAttribute("categories", categories);
        return "front/index";
    }

    @RequestMapping("/{userName}")
    public String index(Model model, Page<Blog> page, BlogQuery query, @PathVariable String userName, HttpSession session) {
        // 根据用户名来查询博主的ID
        Response<User> userResponse = userService.selectByUserName(userName);
        if (userResponse.getResult()==null){
            throw new RuntimeException("没有此博主");
        }
        // 便于搜索 url
        session.setAttribute("username",userName);
        session.setAttribute("userId",userResponse.getResult().getId());
        if (userResponse.isSuccess()) {
            query.setUserId(userResponse.getResult().getId());
        }
        query.setPersonal(0);
        query.setUserName(userName);
        Response<Page<Blog>> response = blogReadService.page(page, query);
        if (!response.isSuccess()) {
            throw new JsonResponseException(response.getError());
        }
        model.addAttribute("page", response.getResult());
        model.addAttribute("query", query);
        List<CategoryDto> categories = categoryService.listAndCount(userResponse.getResult().getId());
        model.addAttribute("categories", categories);
        return "front/index";
    }

    @RequestMapping("/{userName}/category/{id}")
    public String category(Model model, Page<Blog> page, @PathVariable Long id, HttpSession session) {
        BlogQuery query = new BlogQuery();
        query.setUserId((Long) session.getAttribute("userId"));
        query.setPersonal(0);
        query.setCategoryId(id);
        Response<Page<Blog>> response = blogReadService.page(page, query);
        if (!response.isSuccess()) {
            throw new JsonResponseException(response.getError());
        }
        model.addAttribute("page", response.getResult());
        List<CategoryDto> categories = categoryService.listAndCount((Long) session.getAttribute("userId"));
        model.addAttribute("categories", categories);
        return "front/index";
    }

    @RequestMapping("blog/{id}")
    public String blog(HttpServletRequest request, Model model, @PathVariable Long id, HttpSession session) {
        Response<Blog> response = blogReadService.get(id);
        if (!response.isSuccess()) {
            throw new JsonResponseException(response.getError());
        }
        Blog blog = response.getResult();
        model.addAttribute("blog", blog);
        Response<Map<String, Blog>> response2 = blogReadService.getPrevAndNextBlog(id);
        if (!response2.isSuccess()) {
            throw new JsonResponseException(response2.getError());
        }
        model.addAttribute("map", response2.getResult());
        List<CategoryDto> categories = categoryService.listAndCount((Long) session.getAttribute("userId"));
        model.addAttribute("categories", categories);
        String ip = getRemoteHost(request);
        String key = ip + ":view:" + id;
        Object obj = redisUtil.get(key);
        if (obj == null) {
            BlogStatistics blogStatistics = blog.getBlogStatistics();
            blogStatistics.setViewCount(blogStatistics.getViewCount() + 1);
            blogStatisticsService.update(blogStatistics);
            redisUtil.set(key, 1, 3600L);
        }
        return "front/blogWithMyComment";
    }

    @RequestMapping("blog/like/{blogId}")
    @ResponseBody
    public Object blogLike(HttpServletRequest request, @PathVariable Long blogId) {
        String ip = getRemoteHost(request);
        String key = ip + ":like:" + blogId;
        Object obj = redisUtil.get(key);
        if (obj == null) {
            BlogStatistics blogStatistics = blogStatisticsService.get(blogId);
            blogStatistics.setLikeCount(blogStatistics.getLikeCount() + 1);
            blogStatisticsService.update(blogStatistics);
            redisUtil.set(key, 1, 3600L);
            return true;
        } else {
            return false;
        }
    }



}
